//
//  OrderInfoVC.m
//  UHealth
//
//  Created by hanyou on 15/3/18.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "OrderInfoVC.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "iToast.h"
#import "NavView.h"

#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthV2Info.h"


@interface OrderInfoVC ()

@property (nonatomic,strong) NSDictionary   *orderDic;
@property (nonatomic,strong) UIButton       *buyBtn;


@end

@implementation OrderInfoVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
    }
    return self;
}

-(id)initWithDic:(NSDictionary *)dic{
    _orderDic = dic;
    self = [super init];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"orderInfo") andVC:self];
    [self.view addSubview:nav];
    
    UIView *baiView = [[UIView alloc]initWithFrame:CGRectMake(0, kNavHeight+15, WIDTH, 70)];
    baiView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:baiView];
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(15, 5, 60, 60)];
    [img sd_setImageWithURL:[NSURL URLWithString:[_orderDic objectForKey:@"appfile"]] placeholderImage:[UIImage imageNamed:@"pic2"]];
    [baiView addSubview:img];
    
    UILabel *labelM = [[UILabel alloc]initWithFrame:CGRectMake(85, 5, WIDTH - 90, 21)];
    labelM.text = [_orderDic objectForKey:@"shop_name"];
    [baiView addSubview:labelM];
    
    UILabel *labelPri = [[UILabel alloc]initWithFrame:CGRectMake(85, 5+21, WIDTH - 90, 39)];
    labelPri.text = [NSString stringWithFormat:@"%.2f元",[_orderDic[@"saleprice"] floatValue]  *[_orderDic[@"buynum"]intValue]];
    labelPri.font = [UIFont systemFontOfSize:22];
    [baiView addSubview:labelPri];
    
    _buyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _buyBtn.frame = CGRectMake(15, kNavHeight+15 +80, WIDTH-30, 40);
    [_buyBtn.layer setMasksToBounds:YES];
    [_buyBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    _buyBtn.backgroundColor = kBlueColor;
    [_buyBtn setTitle:kLocal(@"pay") forState:UIControlStateNormal];
    [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_buyBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    _buyBtn.tag = 1;
    [self.view addSubview:_buyBtn];
    if ([_orderDic[@"order_status"] isEqualToString:@"已购买"]) {
        _buyBtn.enabled = NO;
        [_buyBtn setTitle:_orderDic[@"order_status"] forState:UIControlStateNormal];
        _buyBtn.backgroundColor = [UIColor grayColor];
    }
    
    UILabel *l0 = [[UILabel alloc]initWithFrame:CGRectMake(15, kNavHeight+15+130, WIDTH - 30, 30)];
    l0.text = kLocal(@"orderInfo");
    [self.view addSubview:l0];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, kNavHeight+15+160, WIDTH-30, 1)];
    line.backgroundColor = kBlueColor;
    [self.view addSubview:line];
    
    UILabel *l1 = [[UILabel alloc]initWithFrame:CGRectMake(15, kNavHeight+15+160, WIDTH - 30, 30)];
    l1.text = [NSString stringWithFormat:@"%@：%@",kLocal(@"order_num"),_orderDic[@"order_no"]];
    [self.view addSubview:l1];
    
    UILabel *l2 = [[UILabel alloc]initWithFrame:CGRectMake(15, kNavHeight+15+190, WIDTH - 30, 30)];
    l2.text = [NSString stringWithFormat:@"%@：%@",kLocal(@"order_time"),_orderDic[@"add_time"]];
    [self.view addSubview:l2];
    
    UILabel *l3 = [[UILabel alloc]initWithFrame:CGRectMake(15, kNavHeight+15+220, WIDTH - 30, 30)];
    l3.text = [NSString stringWithFormat:@"%@：%@",kLocal(@"total_num"),_orderDic[@"buynum"]];
    [self.view addSubview:l3];
    
    UILabel *l4 = [[UILabel alloc]initWithFrame:CGRectMake(15, kNavHeight+15+250, WIDTH - 30, 30)];
    l4.text = [NSString stringWithFormat:@"%@：%.2f",kLocal(@"total_price"),[_orderDic[@"saleprice"] floatValue]  *[_orderDic[@"buynum"]intValue]];
    [self.view addSubview:l4];
    
    UILabel *l5 = [[UILabel alloc]init];
    l5.text = [NSString stringWithFormat:@"%@：%@",kLocal(@"description"),_orderDic[@"js"]];
    l5.numberOfLines = 0;
    CGSize size =[l5.text boundingRectWithSize:CGSizeMake(WIDTH,2000) options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:l5.font} context:nil].size;
    l5.frame =  CGRectMake(15,kNavHeight+15+280, WIDTH-30, size.height);
    [self.view addSubview:l5];


    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - func
-(void)btnClick:(UIButton*)btn
{
    if(kNetID){
        if (!kNetIsOK) {
            [[iToast makeText:kLocal(@"netNoOk")] show];
            return ;
        }
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp?",kBaseUrl];
        NSDictionary *parameters = @{@"action": @"orderpay",
                                     @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"orderid":_orderDic[@"orderid"],
                                     @"pay_mode":@"1"};
        
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //            kDebug(@"Success: %@", operation.responseString);
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            if(type){//成功
                float price = [_orderDic[@"saleprice"] floatValue];
                if(price){//付费的
                    [self pay];
                }else{//免费的
                    [self free];
                }
            }else{
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
        }];
    }
    
}
-(void)free
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/shop.jsp?",kBaseUrl];
    NSDictionary *parameters = @{@"action": @"returnopt",
                                 @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                 @"order_no":_orderDic[@"order_no"],
                                 @"pay_mode":@"1",
                                 @"trade_no":_orderDic[@"order_no"],
                                 @"pay_status":@"1"};
    
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        kDebug(@"Success: %@", operation.responseString);
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        if(type){//成功
            _buyBtn.enabled = NO;
            [_buyBtn setTitle:kLocal(@"have_buy") forState:UIControlStateNormal];
            _buyBtn.backgroundColor = [UIColor grayColor];
        }else{
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
    }];
}
-(void)pay
{
    NSString *tradeNO = [NSString stringWithFormat:@"%@",_orderDic[@"order_no"]];
    NSString *productName = [NSString stringWithFormat:@"%@",_orderDic[@"shop_name"]];
    NSString *productDescription = [NSString stringWithFormat:@"%@",_orderDic[@"js"]];
    float price = [_orderDic[@"saleprice"] floatValue] * [_orderDic[@"buynum"]intValue];
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = kpartner;
    order.seller = kseller;
    order.tradeNO = tradeNO; //订单ID（由商家自行制定）
    order.productName = productName; //商品标题
    order.productDescription = productDescription; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",price]; //商品价格
    order.notifyURL =  knotifyURL; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //    kDebug(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(kprivateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            kDebug(@"reslut.... = %@",resultDic);
            if([resultDic[@"resultStatus"]intValue] == 9000){
                _buyBtn.enabled = NO;
                [_buyBtn setTitle:kLocal(@"have_buy") forState:UIControlStateNormal];
                _buyBtn.backgroundColor = [UIColor grayColor];
            }
        }];
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
